package com.appspot.seqpop.controller;

import java.net.URLDecoder;

import org.slim3.controller.Navigation;

import com.appspot.seqpop.service.UpdateService;
import com.google.appengine.api.datastore.Key;

public class UpdateController extends SeqpopController {

    private UpdateService service = new UpdateService();

    @Override
    public Navigation run() throws Exception {
        Key key = asKey("key");
        if (key == null) {
            throw new Exception("Key is not defined.");
        }
        String[] statistics = paramValues("statistic");
        if (statistics == null) {
            throw new Exception("Specify which statistic(s) should be updated.");
        }

        UpdateService.Updater[] updaters = new UpdateService.Updater[statistics.length];
        for (int index = 0; index < statistics.length; index++) {
            updaters[index] = this.service.getUpdater(statistics[index]);
        }
        Object result = this.service.update(key, updaters);

        String path = param("redirect");
        if (path == null) {
            output(result);
            return null;
        }
        return redirect(URLDecoder.decode(path, "UTF-8"));
    }
}
